#include"heap.h"
void HPinit(PHP php)
{
	assert(php);
	php->arr = NULL;
	php->size = php->capacity = 0;
}
void HPdestroy(PHP php)
{
	assert(php);
	free(php->arr);
	php->arr = NULL;
	php->size = php->capacity = 0;
}
void Swap(HPdatatype* p1, HPdatatype* p2)
{
	HPdatatype tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void Adjustup(HPdatatype*arr, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HPpush(PHP php, HPdatatype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPdatatype* tmp = (HPdatatype*)realloc(php->arr,sizeof(HPdatatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}
		php->arr = tmp;
		php->capacity = newcapacity;
	}
	php->arr[php->size] = x;
	php->size++;
	Adjustup(php->arr, php->size - 1);
}
void Adjustdown(HPdatatype* arr, int n,int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child+1<n && arr[child] >arr[child + 1])
		{
			child++;
		}
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HPpop(PHP php)
{
	assert(php);
	assert(php->size > 0);
	Swap(&php->arr[0], &php->arr[php->size - 1]);
	php->size--;
	Adjustdown(php->arr, php->size, 0);
}
HPdatatype HPtop(PHP php)
{
	assert(php);
	assert(php->size > 0);
	return php->arr[0];
}
bool HPempty(PHP php)
{
	assert(php);
	return php->size == 0;
}